package com.travel.carmen;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;


/**
	Deletes a Note for the Travel Mobile Application Carmen.
	 The View is the Delete Note List View (layout as per delnote.xml) for the application.
	 Provides users with access to notes on their Carmen accounts for deletion. These notes do
	 require a registered user and are retrieved through XMLRPC requests to Carmen (Drupal) Website.
   	@author Arturo Aparicio 
   	@author Edwin Boykin 
   	@author Veena Chengalnaidu
   	@author Anton Ganeshalingam
   	@author Lakshmi Mallampati
   	@author Tarun Morton
   	@author Chantha Thoeun
*/
public class DeleteNote extends Activity implements OnItemClickListener 
{
	private ListView deleteNotesList;
	private String username;
	private String password;
	private String categoryQueried;
	private String deletedNote = Main.BLANK;
	private ArrayAdapter saved_notes;
	private ArrayList<String> toDeleteNotesItems;
	private ArrayList<Integer> toDeleteNotesNID;
	
	// ProgressDialog
	private ProgressDialog dialog;
	private ProgressDialog loading;
	
	private int nid_of_note_to_delete = DrupalNode.INVALID_NID;
	private boolean deleted = false;
	
	@Override
	/**
	   Called when the activity is first created.
	    The UI activities as per delnote.xml are inflated.
	    All listeners and adapters are attached and all settings are
	    made to default.
	 */
	public void onCreate(Bundle bundle)
	{
		super.onCreate(bundle);
		setContentView(R.layout.delnote);
		
		deleteNotesList = (ListView) findViewById (R.id.list_of_my_notes_for_deletion);
		username = getIntent().getStringExtra(getString(R.string.username));
		password = getIntent().getStringExtra(getString(R.string.password));
		categoryQueried = getIntent().getStringExtra(getString(R.string.select_category));
		Log.d("ENTERED DeleteNote WITH", username + "," + password + "," + categoryQueried);
		toDeleteNotesItems = new ArrayList<String>();
		toDeleteNotesNID  = new ArrayList<Integer>();
		
		deleteNotesList.setOnItemClickListener(this);
		
		dialog = new ProgressDialog(this);
		dialog.setMessage("Deleting note...");
		dialog.setIndeterminate(true);

		loading = new ProgressDialog(this);
		loading.setMessage("Retrieving notes...");
		loading.setIndeterminate(true);
		loading.show();
		Thread thread = new Thread() 
		{
			@Override
			public void run() 
			{
				//Used to populate notes
				saved_notes = getSavedNotesAdapter(username, password);
				loadingHandler.sendEmptyMessage(Main.EMPTY);
			}
		};
		thread.start();
	}
	
	
	/**
	   Returns an Adapter populated with user Notes matching a queried Category.
	   @param username Carmen username
	   @param password corresponding account password
	   @return Adapter populated with user Notes matching a queried Category
	 */
	private ArrayAdapter getSavedNotesAdapter(String username, String password)
	{
		try 
		{
			SharedPreferences settings = getSharedPreferences(
					getString(R.string.app_name), 0);
			String apiKey = settings.getString("apiKey", "");
			String serviceDomain = settings.getString("serviceDomain", "");
			String serviceURL = settings.getString("serviceURL", "");
			Log.d("apiKey", apiKey);
			Log.d("domain", serviceDomain);
			Log.d("url", serviceURL);
			DrupalXmlRpcService carmenService = 
				new DrupalXmlRpcService(serviceDomain, apiKey, serviceURL);
			carmenService.connect();
			carmenService.login(username, password);
			
			// get note nid's
			HashMap<String, String>[] nids = 
				carmenService.viewsGet("user_quicknotes", "user_quicknotes");
			// retrieve view for note
			HashMap<String, Object>[] contents = 
				carmenService.viewsGetNotes("user_quicknotes", "user_quicknotes");
			
			for (int i = 0; i < contents.length; i++)
			{
				String nid      = nids[i].get(DrupalNode.NID);
				
				Log.d("[DeleteNotes]", "NID = " + nid);
				Log.d("[DeleteNotes]", contents[i].toString());
				
				Object notesObj = contents[i].get(DrupalNode.NOTE);
				Object catObj   = contents[i].get(DrupalNode.CATEGORY);
				Object[] noteString = (Object[]) notesObj;
				Object[] catString  = (Object[]) catObj;
				HashMap<String, String>[] noteHM = new HashMap[noteString.length];
				HashMap<String, String>[] catHM = new HashMap[catString.length];
				
				for (int j = 0; j < noteHM.length; j++)
				{
					if (noteString[j] instanceof HashMap<?, ?>)
						noteHM[j] = (HashMap<String, String>) noteString[j];
				}
				for (int m = 0; m < catHM.length; m++)
				{
					if (catString[m] instanceof HashMap<?, ?>)
						catHM[m] = (HashMap<String, String>) catString[m];
				}
				
				Log.d("noteHM length", ""+noteHM.length);
				Log.d("catHM length", ""+catHM.length);
				String note = "";
				for (int k = 0; k < noteHM.length; k++)
				{
					note = noteHM[k].get("value");
					Log.d("Note = ", note);
				}
				String category = "";
				for (int n = 0; n < catHM.length; n++)
				{
					category = catHM[n].get("value");
					Log.d("Category = ", category);
				}
				
				if (category != null)
				{
					if (category.equals(categoryQueried))
					{
						toDeleteNotesItems.add(note);
						if (nid != null)
							toDeleteNotesNID.add(Integer.parseInt(nid));
						if (nid == null) // never reached
							toDeleteNotesNID.add(DrupalNode.INVALID_NID);
					}
				}
			}
			
			carmenService.logout();
			Log.d("[DELETE]", "Success!");
			loading.dismiss();
			return new ArrayAdapter<String>(this, 
	    			android.R.layout.simple_list_item_1, toDeleteNotesItems);
			
		}
		catch (Exception e)
		{ 
			Log.d("[DeleteNotes]", "Populating Saved Notes Failed");
			loading.dismiss();
			return new ArrayAdapter<String>(this, 
	    			android.R.layout.simple_list_item_1, toDeleteNotesItems);
		}
	}
	
	
	/**
	   Listener for Note selection for deletion. 
	   	Sends Note information from Carmen (Drupal) website account to caller.
	   @param arg0 Adapter for this Listener
	   @param arg1 View for this Listener
	   @param arg2 Selected Note Position
	   @param arg3 --
	 */
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) 
	{
		deletedNote = deleteNotesList.getAdapter().getItem(arg2).toString();
		nid_of_note_to_delete = toDeleteNotesNID.get(arg2);
		dialog.show();
		Thread thread = new Thread() 
		{
			@Override
			public void run() 
			{
				deleteNoteAt(nid_of_note_to_delete);
				dialogHandler.sendEmptyMessage(Main.EMPTY);
			}
		};
        thread.start();
	}
	
	
	/**
	   Handles thread for deleting a note retrieved through 
	    an XMLRPC request from the Carmen (Drupal) Website.
	   Upon successful deletion, returns control to the Main
	   interface of Carmen Travel Mobile Application.
	 */
	private Handler dialogHandler = new Handler() 
	{
        public void handleMessage(Message msg) 
        {
        	dialog.dismiss();
        	// Finish Activity
        	Intent delIntent = new Intent();
        	delIntent.putExtra(getString(R.string.delete), deletedNote);
        	if (deleted) // precaution: but always reached
        		setResult(Activity.RESULT_OK, delIntent);
        	finish();
        }
	};
	
	
	/**
	   Handles thread for retrieving notes retrieved through 
	    an XMLRPC request from the Carmen (Drupal) Website.
	   Upon successful retrieval, the adapter is populated.
	    Otherwise, a call is made to request a return to the
	     activity caller.
	 */
	private Handler loadingHandler = new Handler() 
	{
        public void handleMessage(Message msg) 
        {	
        	// Empty List
        	if (saved_notes.getCount() == Main.EMPTY)
        		returnToCaller();
        	else
        		deleteNotesList.setAdapter(saved_notes);
        }
	};
	
	
	/**
	   Deletes a DrupalNode that corresponds to the Note requested for
	    deletion by a registered Carmen user. 
	   @param index the Node ID of the DrupalNode to delete.
	   @return true if successfully deleted, else false.
	 */
	public boolean deleteNoteAt(int index)
	{
		try 
		{
			
			SharedPreferences settings = getSharedPreferences(
					getString(R.string.app_name), MODE_PRIVATE);
			String apiKey = settings.getString("apiKey", "");
			String serviceDomain = settings.getString("serviceDomain", "");
			String serviceURL = settings.getString("serviceURL", "");
			DrupalXmlRpcService carmenService = 
				new DrupalXmlRpcService(serviceDomain, apiKey, serviceURL);
			//logging in & deleting node
			carmenService.connect();
			carmenService.login(username, password);
			Log.d("[DeleteNote]", "Deleting NID " + index);
			deleted = carmenService.nodeDelete(index);
			carmenService.logout();
			return deleted;
			
		}
		catch (Exception e)
		{
			Log.d("Delete Failed", e.getMessage());
		}
		return deleted;
	}
	
	
	/**
	   Returns to caller with no Notes. 
	    Category Queried has no Notes for this user to delete.
	 */
	private void returnToCaller()
	{
		Intent emptyIntent = new Intent();
		emptyIntent.putExtra(Main.BLANK, categoryQueried);
		setResult(Main.EMPTY, emptyIntent);
		finish();
	}
}
